﻿using Ldt.CommonCapacitySupport.Business.Model;
using Ldt.DataEngine.DataFlowParse;
using Ldt.DataEngine.LogHandle;
using LdtDataEngin.ModuleDetail.AnalysisModule.SituationPlot;
using LdtDataEngin.ModuleDetail.CommonModule.CommonCapacity;
using LdtJudge.DataEngine.CallInterface;
using LdtJudge.DataEngine.CallInterface.ConfigManager;
using LdtJudge.DataEngine.Common;
using LdtJudge.DataEngine.DataBaseStores;
using LdtJudge.DataEngine.Model.CommModel;
using LdtJudge.DataEngine.Model.DataModel.SysCommon;
using LdtJudge.DataEngine.Model.ElmentModel;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace Ldt.CommonCapacitySupport.Business
{
    /// <summary>
    /// 分析相关业务处理对象
    /// </summary>
    public class AnalysisCapacity_Business
    {

        /// <summary>
        /// 配置对象处理类
        /// </summary>
        private IConfigRetrieval _configRetrieval { get; }

        private string settingCenterUrl = string.Empty;

        /// <summary>
        /// 分析公共能力
        /// </summary>
        /// <param name="configRetrieval">配置数据</param>
        public AnalysisCapacity_Business(IConfigRetrieval configRetrieval)
        {
            _configRetrieval = configRetrieval;
        }

        /// <summary>
        /// 单独分析卷宗数据返回结构化数据
        /// </summary>
        /// <param name="anjid">案件ID</param>
        /// <param name="analysisDoc">卷宗信息</param>
        /// <returns></returns>
        public bodyModel AnalysisSourceDoc(string anjid, Model.AnalysisDocModel analysisDoc, bool dunluo, Dictionary<string, object> dictable)
        {


            bodyModel bodymodel = new bodyModel();
            anjid = Snowflake.Instance().GetId().ToString();
            string sourceContent = string.Empty;
            if (analysisDoc.DocType == 0)
            {
                byte[] filestream = Convert.FromBase64String(analysisDoc.DocFile);
                sourceContent = BllDataHandle.GetDocText(filestream);
            }
            else if (analysisDoc.DocType == 1)
            {
                byte[] filestream = Convert.FromBase64String(analysisDoc.DocFile);
                sourceContent = Encoding.Default.GetString(filestream);
            }
            string district = analysisDoc.District ?? _configRetrieval.GetAppSettingString("district");
            MainInputParameterModel inputParameter = new MainInputParameterModel()
            {
                CaseType = analysisDoc.Anjlx,
                DocID = analysisDoc.Juanzbh,
                SourceContent = sourceContent,
                SD_CaseOnlyID = anjid,
                FilePath = "",
                CaseCause = analysisDoc.Anyid,
                CourtId = "",
                AppId = analysisDoc.AppId,
                CaseID = anjid,
                FL_ID = "",
                SF_ID = "",
                District = district,
                IsSave = false,
                dicTabel = dictable
            };
            ConfigFlowLoad configFlowLoad = new ConfigFlowLoad();
            DataEngin.Assemble.MainComponentBase main = new DataEngin.Assemble.MainComponentBase(configFlowLoad);
            main.inputParameter = inputParameter;
            main.LogShow = DoSetLog;
            main.ProcessShow = DoProcessShow;
            main.ModuleProcessShow = DoModuleProcessShow;
            // 执行分析
            main.GetFlowConfig(ConfigFlowLoad.FlowType.Ana);
            main.ExtractWrap();
            if (main.dataContext.DataLayerOpt != null && main.dataContext.DataLayerOpt.OptimizationXml != null)
            {
                bodymodel.anjianyaosu = main.dataContext.DataLayerOpt.OptimizationXml.OuterXml;

            }
            if (dunluo)
            {
                string json = JsonConvert.SerializeObject(main.dataContext.DataLayerAns.Duanluos);
                bodymodel.an_Duanluos = main.dataContext.DataLayerAns.Duanluos;
            }


            return bodymodel;
        }



        /// <summary>
        /// 单独分析卷宗数据返回结构化数据
        /// </summary>
        /// <param name="anjid">案件ID</param>
        /// <param name="analysisDoc">卷宗信息</param>
        /// <returns></returns>
        public bodyModel AnalysisSourceDocElment(Model.AnalysisApiElement analysisDoc)
        {
            bodyModel bodymodel = new bodyModel();
            string anjid = Snowflake.Instance().GetId().ToString();
            string sourceContent = string.Empty;

            analysisDoc.baseelement = HttpHelp.DeCodeBase64new(65001, analysisDoc.baseelement);
            analysisDoc.mergeelement = HttpHelp.DeCodeBase64new(65001, analysisDoc.mergeelement);


            MainInputParameterModel inputParameter = new MainInputParameterModel()
            {
                CaseType = analysisDoc.anjlx,
                DocID = "CurrentData",
                SourceContent = sourceContent,
                SD_CaseOnlyID = anjid,
                FilePath = "",
                CaseCause = analysisDoc.anyid,
                CourtId = "",
                AppId = analysisDoc.appid,
                CaseID = anjid,
                FL_ID = "",
                SF_ID = "",
                IsSave = false,
                BaseElement = analysisDoc.baseelement,
                MergeElement = analysisDoc.mergeelement
            };
            ConfigFlowLoad configFlowLoad = new ConfigFlowLoad();
            DataEngin.Assemble.MainComponentBase main = new DataEngin.Assemble.MainComponentBase(configFlowLoad);
            main.inputParameter = inputParameter;
            main.LogShow = DoSetLog;
            main.ProcessShow = DoProcessShow;
            main.ModuleProcessShow = DoModuleProcessShow;
            // 执行分析
            main.GetFlowConfig(ConfigFlowLoad.FlowType.Ana, analysisDoc.configflow);
            main.ExtractWrap();
            if (main.dataContext.DataLayerOpt != null && main.dataContext.DataLayerOpt.OptimizationXml != null)
            {
                bodymodel.anjianyaosu = main.dataContext.DataLayerOpt.OptimizationXml.OuterXml;
            }
            return bodymodel;
        }

        /// <summary>
        /// 通过段落数据分析返回结构化数据
        /// </summary>
        /// <param name="analysisParagraph">传入段落数据</param>
        /// <returns></returns>
        public bodyModel AnalysisParagraph(Model.AnalysisParagraphModel analysisParagraph)
        {
            bodyModel bodymodel = new bodyModel();
            string anjid = Snowflake.Instance().GetId().ToString();
            MainInputParameterModel inputParameter = new MainInputParameterModel()
            {
                CaseType = analysisParagraph.CaseType,
                DocID = analysisParagraph.SourceCode,
                SD_CaseOnlyID = anjid,
                FilePath = "",
                CaseCause = analysisParagraph.CaseCause,
                CourtId = "",
                AppId = analysisParagraph.AppId,
                CaseID = anjid,
                laststage = "",
                IsSave = false,
                District = "",
                BCXml = "",
                IsParagraphAnalysis = true,
                ParagraphModels = analysisParagraph.Paragraphs
            };
            ConfigFlowLoad configFlowLoad = new ConfigFlowLoad();
            DataEngin.Assemble.MainComponentBase main = new DataEngin.Assemble.MainComponentBase(configFlowLoad);
            main.inputParameter = inputParameter;
            main.LogShow = DoSetLog;
            main.ProcessShow = DoProcessShow;
            main.ModuleProcessShow = DoModuleProcessShow;
            // 执行分析
            main.GetFlowConfig(ConfigFlowLoad.FlowType.Ana);
            main.ExtractWrap();
            if (main.dataContext.DataLayerOpt != null && main.dataContext.DataLayerOpt.OptimizationXml != null)
            {
                bodymodel.anjianyaosu = main.dataContext.DataLayerOpt.OptimizationXml?.OuterXml;
            }
            return bodymodel;
        }


        public string OffenceElementClass(OffenceElement offenceElement, List<CaseCauseModel> caseCauseModels)
        {
            Dictionary<string, List<CommonPlotorSituation>> diccomm = new Dictionary<string, List<CommonPlotorSituation>>();
            foreach (CaseCauseModel model in caseCauseModels)
            {
                AffordIllegalData affordIllegalData = new AffordIllegalData(null, null,null);
                List<CommonPlotorSituation> commonPlotors = affordIllegalData.MatchAffordValue(offenceElement.Paragraphcode, offenceElement.ParagraphText, model.CC_ID, offenceElement.Anjlx, offenceElement.Juanzbh,offenceElement.District,"");
                diccomm.Add(model.CC_ID, commonPlotors);
            }
            
            return JsonConvert.SerializeObject(diccomm);

        }

        /// <summary>
        /// 根据段落获取
        /// </summary>
        /// <param name="plotExtractModel"></param>
        public void PlotExtract(PlotExtractModel plotExtractModel)
        {


           

        }

        /// <summary>
        /// 根据指定卷宗内容，进行分段处理
        /// </summary>
        /// <param name="anjid">案件ID</param>
        /// <param name="analysisDoc">卷宗分析对象</param>
        /// <returns></returns>
        public IDictionary<string, List<string>> AnalysisDossierParagraph(string anjid, Model.AnalysisDocModel analysisDoc)
        {
            byte[] filestream = Convert.FromBase64String(analysisDoc.DocFile);
            MainInputParameterModel inputParameter = new MainInputParameterModel()
            {
                CaseType = analysisDoc.Anjlx,
                DocID = analysisDoc.Juanzbh,
                SourceContent = BllDataHandle.GetDocText(filestream),
                SD_CaseOnlyID = anjid,
                FilePath = "",
                CaseCause = analysisDoc.Anyid,
                CourtId = "",
                AppId = analysisDoc.AppId,
                CaseID = anjid,
                FL_ID = "",
                SF_ID = "",
                IsSave = false
            };
            ConfigFlowLoad configFlowLoad = new ConfigFlowLoad();
            DataEngin.Assemble.MainComponentBase main = new DataEngin.Assemble.MainComponentBase(configFlowLoad);
            main.inputParameter = inputParameter;
            main.GetFlowConfig(ConfigFlowLoad.FlowType.Ana);
            main.ExtractWrap();
            var paralist = main.dataContext.DataLayerAns.Duanluos;
            var partext = paralist.GroupBy(p => p.Duanluobianhao).ToList().ToDictionary(a => a.Key, b => b.Select(c => c.Duanluoneirong).ToList());
            return partext;
        }

        /// <summary>
        /// 匹配争议焦点
        /// </summary>
        /// <param name="orignalText">原文信息</param>
        /// <param name="causeid">案件id</param>
        /// <param name="sourcename">卷宗编号</param>
        /// <param name="paragraphCode">段落编号</param>
        /// <param name="message">输出消息</param>
        /// <returns></returns>
        public IDictionary<string, string> MatchArgument(string orignalText, string causeid, string sourcename, string paragraphCode, out string message)
        {
            ArgumentFocusHandle argumentFocusHandle = new ArgumentFocusHandle();
            return argumentFocusHandle.GetArgumentFocus(orignalText, causeid, sourcename, paragraphCode, out message);
        }

        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="text">日志内容</param>
        /// <param name="logType">日志类型</param>
        internal void DoSetLog(string text, LogMessageType logType)
        {
            LogHandle.LogHType log = LogHandle.LogHType.Info;
            foreach (LogHandle.LogHType typ in Enum.GetValues(typeof(LogHandle.LogHType)))
            {
                if (((int)logType) == ((int)typ))
                {
                    log = typ;
                    break;
                }
            }
            //写入记录日志
            LogHandle.GetInitLogHandle.LogWrite(log, "  数据同步接口： " + text);
        }


        internal void DoProcessShow(string fileId, int nvalue, MainInputParameterModel inputParameterModel)
        {

        }
        public List<string> flist = new List<string>();
        internal void DoModuleProcessShow(string moduleName, int nvalue, MainInputParameterModel inputParameterModel)
        {
            if (moduleName.IndexOf("_") > -1)
            {
                flist.Add(moduleName);
            }

        }

        internal void DoModularModel(string dataLayerStores, string type)
        {

        }

    }
}
